package com.ffcc.fitness.websocket.handler;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.net.URI;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Spring WebSocket处理器
 */
public class SpringWebSocketHandler extends TextWebSocketHandler {
    
    // 存储用户连接
    private static final Map<String, WebSocketSession> SESSIONS = new ConcurrentHashMap<>();
    
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String userId = extractUserIdFromSession(session);
        System.out.println("=== Spring WebSocket连接建立 ===");
        System.out.println("用户ID: " + userId);
        System.out.println("Session ID: " + session.getId());
        System.out.println("URI: " + session.getUri());
        
        SESSIONS.put(userId, session);
        
        // 发送欢迎消息
        session.sendMessage(new TextMessage("Spring WebSocket连接成功，用户ID: " + userId));
    }
    
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String userId = extractUserIdFromSession(session);
        System.out.println("=== 收到Spring WebSocket消息 ===");
        System.out.println("用户ID: " + userId);
        System.out.println("消息: " + message.getPayload());
        
        // 回显消息
        session.sendMessage(new TextMessage("Echo: " + message.getPayload()));
    }
    
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        String userId = extractUserIdFromSession(session);
        System.out.println("=== Spring WebSocket连接关闭 ===");
        System.out.println("用户ID: " + userId);
        System.out.println("关闭状态: " + status);
        
        SESSIONS.remove(userId);
    }
    
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        String userId = extractUserIdFromSession(session);
        System.err.println("=== Spring WebSocket传输错误 ===");
        System.err.println("用户ID: " + userId);
        System.err.println("错误: " + exception.getMessage());
        exception.printStackTrace();
    }
    
    /**
     * 从WebSocket会话中提取用户ID
     */
    private String extractUserIdFromSession(WebSocketSession session) {
        try {
            URI uri = session.getUri();
            if (uri != null) {
                String path = uri.getPath();
                // 从路径中提取用户ID，路径格式: /websocket/spring/{userId}
                String[] segments = path.split("/");
                if (segments.length >= 3) {
                    return segments[segments.length - 1];
                }
            }
        } catch (Exception e) {
            System.err.println("提取用户ID失败: " + e.getMessage());
        }
        return "unknown";
    }
}
